<template>
    <div class="system-user-container layout-padding">
        <el-card shadow="hover" class="layout-padding-auto">
            <div class="system-user-search">
                <el-row :gutter="20">
                    <el-col :span="24" class="col-center">
                        <el-input size="default" class="mt10" v-model="state.tableData.param.nickName" placeholder="请输入用户昵称"
                            clearable @keyup.enter="handleQuery" v-auths="['system:user:query']" />
                        <el-select v-model="state.tableData.param.sex" size="default" class="mt10" placeholder="请选择用户性别"
                            clearable>
                            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                                :value="dict.value" />
                        </el-select>
                        <el-date-picker clearable v-model="state.dateRangeLoginDate" type="date" value-format="YYYY-MM-DD"
                            placeholder="请选择最后登录时间" size="default" class="mt10" style="max-width: 250px;">
                        </el-date-picker>
                        <el-button size="default" class="mt10" type="primary" @click="getTableData()">
                            <el-icon>
                                <ele-Search />
                            </el-icon>
                            搜索
                        </el-button>
                        <el-button size="default" class="mt10" type="info" @click="resetQuery()">
                            <el-icon>
                                <ele-Refresh />
                            </el-icon>
                            重置
                        </el-button>
                    </el-col>
                    <el-col :span="24">
                        <el-button size="default" class="mt10" type="primary" plain :icon="'ele-Plus'" @click="handleAdd"
                            v-auths="['system:user:add']">新增
                        </el-button>
                        <el-button size="default" class="mt10" type="success" plain :icon="'ele-Edit'" :disabled="single"
                            @click="handleUpdate" v-auths="['system:user:edit']">修改
                        </el-button>
                        <el-button size="default" class="mt10" type="danger" plain :icon="'ele-Delete'" :disabled="multiple"
                            @click="handleDelete" v-auths="['system:user:remove']">删除
                        </el-button>
                        <el-button size="default" class="mt10" type="warning" plain :icon="'ele-Download'"
                            @click="handleExport" v-auths="['system:user:export']">导出
                        </el-button>
                    </el-col>
                </el-row>
            </div>
            <el-table v-loading="state.loading" :data="state.tableData.userList" @selection-change="handleSelectionChange"
                style="width: 100%">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="用户ID" align="center" prop="userId" v-if="true" show-overflow-tooltip />
                <el-table-column label="部门ID" align="center" prop="deptId" show-overflow-tooltip />
                <el-table-column label="用户账号" align="center" prop="userName" show-overflow-tooltip />
                <el-table-column label="用户昵称" align="center" prop="nickName" show-overflow-tooltip />
                <el-table-column label="用户邮箱" align="center" prop="email" show-overflow-tooltip />
                <el-table-column label="手机号码" align="center" prop="phonenumber" show-overflow-tooltip />
                <el-table-column label="用户性别" align="center" prop="sex" show-overflow-tooltip>
                    <template #default="scope">
                        <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
                    </template>
                </el-table-column>
                <el-table-column label="头像地址" align="center" prop="avatar" width="100">
                    <template #default="scope">
                        <el-avatar :size="60" :src="scope.row.avatar">
                            <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                        </el-avatar>
                    </template>
                </el-table-column>
                <el-table-column label="帐号状态" align="center" prop="status" show-overflow-tooltip />
                <el-table-column label="最后登录IP" align="center" prop="loginIp" show-overflow-tooltip />
                <el-table-column label="最后登录时间" align="center" prop="loginDate" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{ scope.row.loginDate }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="100" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" :icon="'ele-Edit'" @click="handleUpdate(scope.row)"
                            :disabled="scope.row.admin" v-auths="['system:user:edit']">修改
                        </el-button>
                        <el-button link type="primary" :icon="'ele-Delete'" @click="handleDelete(scope.row)"
                            :disabled="scope.row.admin" v-auths="['system:user:remove']">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange"
                class="mt15 paginationFlex" :pager-count="5" :page-sizes="[10, 20, 30]"
                v-model:current-page="state.tableData.param.pageNum" background
                v-model:page-size="state.tableData.param.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="state.tableData.total">
            </el-pagination>
            <!-- 添加或修改用户信息对话框 -->
            <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" max-width="800px" width="90%"
                append-to-body>
                <el-form ref="userRef" :model="form" :rules="state.rules" size="default" label-width="90px">
                    <el-row :gutter="35">
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="部门ID" prop="deptId">
                                <el-input v-model="form.deptId" placeholder="请输入部门ID" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="用户账号" prop="userName">
                                <el-input v-model="form.userName" placeholder="请输入用户账号" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="用户昵称" prop="nickName">
                                <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="用户邮箱" prop="email">
                                <el-input v-model="form.email" placeholder="请输入用户邮箱" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="手机号码" prop="phonenumber">
                                <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="用户性别" prop="sex">
                                <el-select v-model="form.sex" placeholder="请选择用户性别">
                                    <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="头像地址" prop="avatar">
                                <imgUpload :img="form.avatar" @uploadSuccess="uploadSuccess" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                            <el-form-item label="密码" prop="password">
                                <el-input v-model="form.password" placeholder="请输入密码" />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                        <el-button @click="cancel">取 消</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup name="User" lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUser } from "/@/api/system/user";
import { useDict } from '/@/utils/dict';
import { download } from '/@/utils/tool';
import { ref, reactive, onMounted } from "vue";

const { sys_user_sex } = useDict('sys_user_sex');

import { defineAsyncComponent } from 'vue';
const imgUpload = defineAsyncComponent(() => import('/@/components/imageUpload/index.vue'));
const uploadSuccess = (img: string) => {
    form.value.remark = img;
}


interface UserForm {
    userId?: string;
    deptId?: string;
    userName?: string;
    nickName?: string;
    userType?: string;
    email?: string;
    phonenumber?: string;
    sex?: string;
    avatar?: string;
    password?: string;
    status?: string;
    delFlag?: string;
    loginIp?: string;
    loginDate?: string;
    createBy?: string;
    createTime?: string;
    updateBy?: string;
    updateTime?: string;
    remark?: string;
}

const buttonLoading = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const userRef = ref();
const form = ref(<any>{});
const state = reactive({
    dateRangeLoginDate: [],
    dateRangeCreateTime: [],
    dateRangeUpdateTime: [],
    loading: false,
    ruleForm: {} as UserForm,
    tableData: {
        data: [],
        total: 0,
        userList: [],
        param: {
            pageNum: 1,
            pageSize: 10,
            nickName: undefined,
            sex: undefined,
            status: undefined,
            loginDate: undefined,
        }
    },
    dialog: {
        isShowDialog: false,
        type: '',
        title: '',
        submitTxt: '',
    },
    rules: {
        userName: [
            { required: true, message: "用户账号不能为空", trigger: "blur" }
        ],
        nickName: [
            { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
        email: [
            { required: true, message: "用户邮箱不能为空", trigger: "blur" }
        ],
        phonenumber: [
            { required: true, message: "手机号码不能为空", trigger: "blur" }
        ],
        sex: [
            { required: true, message: "用户性别不能为空", trigger: "change" }
        ],
        avatar: [
            { required: true, message: "头像地址不能为空", trigger: "blur" }
        ],
        password: [
            { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        status: [
            { required: true, message: "帐号状态不能为空", trigger: "change" }
        ],
    }
});

/** 查询用户信息列表 */
const getTableData = () => {
    state.loading = true;
    useUser().listUser(state.tableData.param).then(response => {
        state.tableData.userList = response.rows;
        state.tableData.total = response.total;
        state.loading = false;
    });
}

// 取消按钮
function cancel() {
    state.dialog.isShowDialog = false;
    resetParamData();
}

// 表单重置
function resetParamData() {
    form.value = {
    };
}

/** 搜索按钮操作 */
function handleQuery() {
    state.tableData.param.pageNum = 1;
    getTableData();
}

/** 重置按钮操作 */
function resetQuery() {
    state.dateRangeLoginDate = [];
    state.dateRangeCreateTime = [];
    state.dateRangeUpdateTime = [];
    state.tableData.param = {
        pageNum: 1,
        pageSize: 10,
        nickName: undefined,
        sex: undefined,
        status: undefined,
        loginDate: undefined,
    };
    handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.userId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    resetParamData();
    state.dialog.isShowDialog = true;
    state.dialog.title = "添加用户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    state.loading = true
    resetParamData();
    const _userId = row.userId || ids.value
    useUser().getUser(_userId).then(response => {
        state.loading = false;
        form.value = response.data;
        state.dialog.isShowDialog = true;
        state.dialog.title = "修改用户信息";
    });
}

/** 提交按钮 */
function submitForm() {
    userRef.value.validate(valid => {
        if (valid) {
            buttonLoading.value = true;
            if (form.value.userId != null) {
                useUser().updateUser(form.value).then(response => {
                    ElMessage.success(response.msg);
                    state.dialog.isShowDialog = false;
                    getTableData();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            } else {
                useUser().addUser(form.value).then(response => {
                    getTableData();
                    ElMessage.success(response.msg);
                    state.dialog.isShowDialog = false;
                }).finally(() => {
                    buttonLoading.value = false;
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _userIds = row.userId || ids.value;
    ElMessageBox.confirm('是否确认删除用户信息编号为"' + _userIds + '"的数据项？').then(function () {
        state.loading = true;
        return useUser().delUser(_userIds);
    }).then((res) => {
        state.loading = true;
        getTableData();
        ElMessage.success(res.msg);
    }).catch(() => {
    }).finally(() => {
        state.loading = false;
    });
}

/** 导出按钮操作 */
function handleExport() {
    download('system/user/export', {
        ...state.tableData.param
    }, `user_${new Date().getTime()}.xlsx`)
}


// 分页改变
const onHandleSizeChange = (val: number) => {
    state.tableData.param.pageSize = val;
    getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
    state.tableData.param.pageNum = val;
    getTableData();
};
// 页面加载时
onMounted(() => {
    getTableData();
});
</script>

<style scoped lang="scss">
.system-user-container {
    :deep(.el-card__body) {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: auto;

        .el-table {
            flex: 1;
        }

        .layout-padding-auto {
            padding: 0 0;

            .system-user-search {
                margin: 0 0;
            }
        }
    }
}

.mt10 {
    max-width: 140px;
    margin: 10px 0 10px 10px;
}

.el-upload__tip {
    p {
        display: flex;
        align-items: center;

        .el-link {
            font-size: 12px;
            vertical-align: baseline;
        }
    }

    span {
        display: flex;
        align-items: center;
        margin: 0 8px;
    }
}
</style>